package com.fanketly.funacg2.ui.screen

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.outlined.Cancel
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.paging.LoadState
import androidx.paging.compose.LazyPagingItems
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.itemKey
import com.fanketly.funacg2.data.model.WorkList
import com.fanketly.funacg2.data.paging.rememberLazyListState
import com.fanketly.funacg2.ui.components.ControllerIcon
import com.fanketly.funacg2.ui.components.HomeListCard
import com.fanketly.funacg2.ui.navigation.toShowThisTagScreen
import com.fanketly.funacg2.ui.theme.FunACG2Theme
import com.fanketly.funacg2.ui.theme.dp8
import com.fanketly.funacg2.ui.viewmodels.HomeViewModel
import com.fanketly.funacg2.ui.viewmodels.SearchViewModel
import com.ramcosta.composedestinations.annotation.Destination
import com.ramcosta.composedestinations.navigation.DestinationsNavigator
import kotlinx.coroutines.launch

@Destination
@Composable
fun SearchScreen(
    searchViewModel: SearchViewModel = hiltViewModel(),
    homeViewModel: HomeViewModel,
    navigator: DestinationsNavigator,
) {
    Column(Modifier.fillMaxSize()) {
        val lazyPagingItems = searchViewModel.pager.collectAsLazyPagingItems()
        val lazyListState = lazyPagingItems.rememberLazyListState()
//        val lazyListState = rememberLazyListState()
        val coroutineScope = rememberCoroutineScope()
        Search(modifier = Modifier
            .padding(8.dp)
            .fillMaxWidth(), onSearch = {
            coroutineScope.launch {
                lazyListState.scrollToItem(0)
//                delay(200L)
                searchViewModel.search(it)
                lazyPagingItems.refresh()
            }

        })
        SearchCardList(
            lazyPagingItems = lazyPagingItems,
            lazyListState = lazyListState,
            getAudio = homeViewModel::getAudio,
            onTagClick = {
                navigator.toShowThisTagScreen(it,homeViewModel)
            })
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SearchCardList(
    lazyPagingItems: LazyPagingItems<WorkList.Work>,
    lazyListState: LazyListState,
    onTagClick: (tag: Int) -> Unit,
    getAudio: (WorkList.Work) -> Unit,
) {
    if (lazyPagingItems.loadState.refresh == LoadState.Loading) {
        LinearProgressIndicator(
            modifier = Modifier.fillMaxWidth()
        )
    } else LazyColumn(
        modifier = Modifier.fillMaxSize(),
        state = lazyListState,
        horizontalAlignment = Alignment.CenterHorizontally,
    ) {
        items(lazyPagingItems.itemCount, key = lazyPagingItems.itemKey { it.id }) { index ->
            val work = lazyPagingItems[index]
            if (work == null) {
                ElevatedCard(
                    onClick = {},
                    modifier = Modifier
                        .fillMaxWidth(0.9f)
                        .height(300.dp)
                        .padding(top = dp8, bottom = dp8),
                ) {}
            } else {
                HomeListCard(work, onTagClick = onTagClick) {
                    getAudio(work)
                }
            }
        }
        if (lazyPagingItems.loadState.append == LoadState.Loading) {
            item {
                CircularProgressIndicator(
                    modifier = Modifier
                        .fillMaxWidth()
                        .wrapContentWidth(Alignment.CenterHorizontally)
                )
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class, ExperimentalComposeUiApi::class)
@Composable
fun Search(modifier: Modifier = Modifier, onSearch: (String) -> Unit) {
    var text by rememberSaveable {
        mutableStateOf("")
    }
    var isShowDel by rememberSaveable {//是否显示删除
        mutableStateOf(false)
    }
    val keyboardController = LocalSoftwareKeyboardController.current
    OutlinedTextField(
        modifier = modifier,
        value = text,
        singleLine = true,
        onValueChange = {
            if (!isShowDel) isShowDel = true
            text = it
        },
        keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
        keyboardActions = KeyboardActions(onSearch = {
            isShowDel = false
            keyboardController?.hide()
            onSearch(text)
        }),
        label = { Text("请输入RJ号或名称") }, leadingIcon = {
            IconButton(onClick = {
                isShowDel = false
                keyboardController?.hide()
                onSearch(text)
            }, modifier = Modifier.size(30.dp)) {
                ControllerIcon(imageVector = Icons.Filled.Search)
            }
        }, trailingIcon = {
            if (isShowDel) IconButton(onClick = {
                text = ""
                isShowDel = false
            }, modifier = Modifier.size(26.dp)) {
                ControllerIcon(imageVector = Icons.Outlined.Cancel)
            }
        })
}

@Preview
@Composable
private fun SearchPreview() {

    FunACG2Theme {
        Box(modifier = Modifier.background(Color.White)) {
            Search(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(50.dp)
            ) {

            }
            Text(text = "3123")
        }
    }
}